package com.example.springmvc_demo4.controller;

import com.example.springmvc_demo4.controller.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class LoginController {
    //访问login方法，使用url： http://localhost:8080/login，跳转到login.html页面
    @RequestMapping("/login")
    public String openLoginPage(){
        //返回值直接写templates文件夹下的网页文件名称，不需要加.html后缀
        return "login";
    }

    //在login方法中接受用户提交的账号和密码,用户是通过网页使用form表单提交的数据
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String login(@RequestParam("username") String name,@RequestParam("password") String password){
        System.out.println("username:"+name+",password:"+password);
        if(name.equals("admin")&&password.equals("123")){
            return "redirect:/";
        }
        return "login";
    }
    //方法参数使用实体类
    @RequestMapping(value = "/login2",method = RequestMethod.POST)
    public ModelAndView login2(User user, ModelAndView mv){
        System.out.println("username:"+user.getUsername()+",password:"+user.getPassword());
        if (user.getUsername().equals("admin")&&user.getPassword().equals("123")){
            mv.setViewName("redirect:/");
            return mv;
        }
        //如果登陆失败，需要返回提示信息和重新返回到login.html页面
        mv.addObject("msg","登陆失败");//设置返回的数据
        mv.setViewName("login");
        return mv;
    }
    //@GetMapping("/login3")约等于@RequestMapping(value = "/login3",method = RequestMethod.GET)
    @GetMapping("/login3")
    public String login3(User user){
        System.out.println(user);
        return "index";
    }
}
